package com.example.yichuangyun.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;

import com.example.yichuangyun.R;
import com.example.yichuangyun.application.MyApplication;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.FragmentIndexBinding;
import com.example.yichuangyun.dialog.MyDialog;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.business.LabelModel;
import com.example.yichuangyun.model.index.DaiBanDataModel;
import com.example.yichuangyun.model.index.MonthDataModel;
import com.example.yichuangyun.model.index.TodayListModel;
import com.example.yichuangyun.mvvm.base.BaseFragment;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.mvvm.ui.activity.AddressBookActivity;
import com.example.yichuangyun.mvvm.ui.activity.order.OrderListActivity;
import com.example.yichuangyun.ui.activity.business.AddBusinessActivity;
import com.example.yichuangyun.ui.activity.business.SearchBusinessActivity;
import com.example.yichuangyun.ui.activity.follow.FollowListActivity;
import com.example.yichuangyun.ui.activity.index.MyEventActivity;
import com.example.yichuangyun.ui.activity.index.StatisticsDailyActivity;
import com.example.yichuangyun.ui.adapter.DaiBanEventAdapter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.DateUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UMengUtil;
import com.google.gson.Gson;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 首页
 */
public class IndexFragment extends BaseFragment<FragmentIndexBinding, BaseViewModel> {

    private String currentSelectDate;
    private DaiBanEventAdapter adapter;
    private List<DaiBanDataModel.RecordsBean> daiBanData = new ArrayList<>();
    /**
     * 拨打的电话号码
     */
    private String mTelNumber;
    private String userId;
    private MyDialog myDialog;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        initDialog();
        binding.smartRefreshLayout.setEnableOverScrollDrag(true);
        binding.tvCurrentDate.setText(DateUtil.getCurrentMonthC());
        currentSelectDate = DateUtil.getCurrentDay();
        getTodayData();
        getMonthData();
        getMonthCommission();
//        getBacklogSchedule(currentSelectDate);
//        initMonthRequest(DateUtil.getCurrentDay());
    }

//    private void initMonthRequest(String trackDateNext) {
//        JSONObject requestDate = new JSONObject();
//        try {
//            requestDate.put("trackDateNextStart", trackDateNext);
//            requestDate.put("trackDateNextEnd", DateUtil.getLastDayOfChooseMonth(trackDateNext));
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
//        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getMonthBlockLog(requestBody), new MyObserver<HttpRespond<List<String>>>() {
//            @Override
//            protected void onSuccess(HttpRespond<List<String>> listHttpRespond) {
//                if (listHttpRespond.code == Constant.SUCCESS) {
//                    if (listHttpRespond.data != null && listHttpRespond.data.size() > 0) {
//                        List<String> list = listHttpRespond.data;
//                        Map<String, Calendar> map = new HashMap<>();
//                        for (String s : list) {
//                            Calendar calendar = new Calendar();
//                            calendar.setYear(Integer.parseInt(s.substring(0, 4)));
//                            calendar.setMonth(Integer.parseInt(s.substring(5, 7)));
//                            calendar.setDay(Integer.parseInt(s.substring(8, 10)));
//                            map.put(calendar.toString(), calendar);
//                        }
//                        binding.calendarView.setSchemeDate(map);
//                    }
//                }
//            }
//        });
//    }

    @Override
    public void initCtrl() {
        adapter = new DaiBanEventAdapter(mContext, daiBanData);
        binding.recyclerView.setAdapter(adapter);
    }

    /**
     * 今日统计
     */
    private void getTodayData() {
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("dateTimeStart", DateUtil.getNowYMD());
            requestDate.put("dateTimeEnd", DateUtil.getNowYMD());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getTodayData(requestBody), new MyObserver<HttpRespond<TodayListModel>>() {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onSuccess(HttpRespond<TodayListModel> todayListModelHttpRespond) {
                if (Constant.SUCCESS == todayListModelHttpRespond.code) {
                    if (todayListModelHttpRespond.data != null && todayListModelHttpRespond.data.getRecords() != null) {
                        List<TodayListModel.TodayModel> records = todayListModelHttpRespond.data.getRecords();
                        if (records.size() > 0) {
                            if (!TextUtils.isEmpty(records.get(0).getNewCustomer())) {
                                binding.tvAddBusinessCount.setText(records.get(0).getNewCustomer());
                            }
                            binding.tvCallCount.setText(records.get(0).getCallNum());
                            binding.tvCallTime.setText(DateUtil.getTimeBySecond2(records.get(0).getCallTime()));
                        } else {
                            binding.tvAddBusinessCount.setText("0");
                            binding.tvCallTime.setText("00:00:00");
                        }
                    }
                }
            }
        });
    }

    /**
     * 本月业绩
     */
    private void getMonthData() {
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getMonthData(MyApplication.manager.getJobNumber()), new MyObserver<HttpRespond<MonthDataModel>>() {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onSuccess(HttpRespond<MonthDataModel> listHttpRespond) {
                if (Constant.SUCCESS == listHttpRespond.code) {
                    if (listHttpRespond.data != null) {
                        userId = listHttpRespond.data.getUserId();
                        binding.tvSignOrderCount.setText(String.valueOf(listHttpRespond.data.getSignCount()));
                        if (TextUtils.isEmpty(listHttpRespond.data.getRzehtTotal()) || listHttpRespond.data.getRzehtTotal().equals("0")) {
                            binding.tvMonthMoney.setText("0.00");
                        } else {
                            binding.tvMonthMoney.setText(listHttpRespond.data.getRzehtTotal());
                        }
                    }
                }
            }
        });
    }

    /**
     * 本月佣金
     */
    private void getMonthCommission() {
        Map<String, Object> map = new HashMap<>();
        map.put("isMy","1");
        map.put("page","1");
        map.put("pageSize","10");
        map.put("roadCommission","0");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(map));
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getMonthCommission(requestBody), new MyObserver<HttpRespond<MonthDataModel>>() {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onSuccess(HttpRespond<MonthDataModel> listHttpRespond) {
                if (Constant.SUCCESS == listHttpRespond.code) {
                    if (listHttpRespond.data != null) {
                        binding.tvCommMoney.setText(listHttpRespond.data.getSameMonth());
                    }
                }
            }
        });
    }

    /**
     * 待办事项
     */
//    private void getBacklogSchedule(String currentSelectDate) {
//        JSONObject requestDate = new JSONObject();
//        try {
//            requestDate.put("trackDateNext", currentSelectDate);
//            requestDate.put("current", 1);
//            requestDate.put("size", 5);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
//        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getBacklogSchedule(requestBody), new MyObserver<HttpRespond<DaiBanDataModel>>() {
//            @SuppressLint("SetTextI18n")
//            @Override
//            protected void onSuccess(HttpRespond<DaiBanDataModel> daiBanDataModelHttpRespond) {
//                if (Constant.SUCCESS == daiBanDataModelHttpRespond.code) {
//                    if (daiBanDataModelHttpRespond.data != null && daiBanDataModelHttpRespond.data.getRecords() != null) {
//                        List<DaiBanDataModel.RecordsBean> records = daiBanDataModelHttpRespond.data.getRecords();
//                        if (isAdded()) {
//                            binding.tvEventCount.setText(mContext.getString(R.string.to_do_event_count, daiBanDataModelHttpRespond.data.getTotal()));
//                        }
//                        daiBanData = records;
//                        adapter.onRefresh(daiBanData);
//                    }
//                }
//            }
//        });
//    }
    @Override
    protected void initClick() {
        // 搜索
        binding.ivSearch.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                JumpIntent.jump(getActivity(), SearchBusinessActivity.class);
            }
        });

        // 订单列表
        binding.tvOrderList.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                JumpIntent.jump(getActivity(), OrderListActivity.class);
            }
        });

        // 通讯录
        binding.tvAddressBook.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                UMengUtil.setCountEventId(Constant.HOME_ADDRESS_BOOK);
                showLoadingDialog();
                RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getContactsType(), new MyObserver<HttpRespond<List<LabelModel>>>() {
                    @Override
                    protected void onSuccess(HttpRespond<List<LabelModel>> listHttpRespond) {
                        dismissLoadingDialog();
                        if (listHttpRespond.code == Constant.SUCCESS) {
                            List<LabelModel> list = listHttpRespond.data;
                            if (null != list && !list.isEmpty()) {
                                Bundle bundle = new Bundle();
                                bundle.putSerializable(Constant.listKey, (Serializable) list);
                                JumpIntent.jump(getActivity(), AddressBookActivity.class, bundle);
                            } else {
                                ToastHelper.show(mContext.getString(R.string.no_permission));
                            }
                        } else {
                            ToastHelper.show(listHttpRespond.msg);
                        }
                    }

                    @Override
                    protected void onFail(Throwable e) {
                        super.onFail(e);
                        dismissLoadingDialog();
                    }
                });
            }
        });

        // 新增商机
        binding.tvMyBusiness.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                UMengUtil.setCountEventId(Constant.HOME_ADD_BUSINESS);
                JumpIntent.jump(getActivity(), AddBusinessActivity.class);
            }
        });

        // 跟进记录
        binding.tvFollowRecord.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                JumpIntent.jump(getActivity(), FollowListActivity.class);
            }
        });

        // 今日统计
        binding.rlTodayData.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                UMengUtil.setCountEventId(Constant.HOME_TODAY_DATA);
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.flagKey, 0);
                JumpIntent.jump(getActivity(), StatisticsDailyActivity.class, bundle);
            }
        });

        // 佣金统计
        binding.llCommissionAccount.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.flagKey, 1);
                JumpIntent.jump(getActivity(), StatisticsDailyActivity.class, bundle);
            }
        });

        // 入账额（合同）
        binding.llEnterAccount.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.flagKey, 2);
                bundle.putString(Constant.userIdKey, userId);
                JumpIntent.jump(getActivity(), StatisticsDailyActivity.class, bundle);
            }
        });

        binding.llSignCount.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.flagKey, 2);
                bundle.putString(Constant.userIdKey, userId);
                JumpIntent.jump(getActivity(), StatisticsDailyActivity.class, bundle);
            }
        });

        // 待办事项
        binding.rlEvent.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                JumpIntent.jump(getActivity(), MyEventActivity.class);
            }
        });

        // 日历
        binding.calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                String month;
                String day;
                String year = calendar.getYear() + "";
                month = calendar.getMonth() < 10 ? "0" + calendar.getMonth() : String.valueOf(calendar.getMonth());
                day = calendar.getDay() < 10 ? "0" + calendar.getDay() : String.valueOf(calendar.getDay());
                currentSelectDate = mContext.getString(R.string.year_month_day2, year, month, day);
                binding.tvCurrentDate.setText(mContext.getString(R.string.year_month, year, month));
//                getBacklogSchedule(currentSelectDate);
            }
        });

        binding.smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            binding.smartRefreshLayout.finishRefresh(500);
            getTodayData();
            getMonthData();
            getMonthCommission();
//            getBacklogSchedule(currentSelectDate);
//            initMonthRequest(DateUtil.getCurrentDay());
        });

        adapter.setOnCallListener(model -> {
            mTelNumber = model.getTelNumber();
            checkCallNum(mTelNumber);
        });
    }

    private void initDialog() {
        myDialog = new MyDialog(getActivity()) {
            @Override
            public void rightClick() {
                if (!XXPermissions.isGrantedPermission(mContext, Permission.CALL_PHONE)) {
                    XXPermissions.with(getActivity())
                            .permission(Permission.CALL_PHONE)
                            .request((permissions, all) -> {
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_CALL);
                                intent.setData(Uri.parse("tel:" + mTelNumber));
                                startActivity(intent);
                            });
                } else {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_CALL);
                    intent.setData(Uri.parse("tel:" + mTelNumber));
                    startActivity(intent);
                }
            }
        };
    }

    /**
     * 获取拨打电话次数
     */
    private void checkCallNum(String mTelNumber) {
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().checkPhone(mTelNumber), new MyObserver<HttpRespond<Boolean>>() {
            @Override
            protected void onSuccess(HttpRespond<Boolean> booleanHttpRespond) {
                if (Constant.SUCCESS == booleanHttpRespond.code) {
                    if (booleanHttpRespond.data) {
                        ToastHelper.show(mContext.getString(R.string.call_fail));
                    } else {
                        myDialog.setText(mTelNumber, mContext.getString(R.string.confirm_call_num));
                        myDialog.showDialog();
                    }
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (!TextUtils.isEmpty(eventBusModel.getMsg())) {
                String msg = eventBusModel.getMsg();
                if (msg.equals(Constant.refreshTodayData) || msg.equals(Constant.refreshBusinessList)) {
                    getTodayData();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
